package com.guoyihao.codesandbox.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.guoyihao.codesandbox.model.ExecuteCodeRequest;
import com.guoyihao.codesandbox.model.ExecuteCodeResponse;
import com.guoyihao.codesandbox.model.ExecuteMessage;
import com.guoyihao.codesandbox.model.JudgeInfo;
import com.guoyihao.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 实现Java代码编译复用的抽象类
 */
@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandBox {

    private final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private final String MAIN_CLASS = "Main";

    private final Long TIME_OUT = 1000L;

    /**
     * 1.把用户的代码保存为文件
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code){
        //获取当前工作目录
        String userDir = System.getProperty("user.dir");
        //得到tmpCode路径
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();

        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        //将代码写入到文件中
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        log.info("用户代码位置：" + userCodeFile);
        return userCodeFile;
    }

    /**
     * 2.编译代码，得到 class 文件
     * @param absolutePath class文件的路径
     * @return
     */
    public ExecuteMessage compileCode(String absolutePath){
        ExecuteMessage executeMessage = null;
        String compileCmd = String.format("javac -encoding utf-8 %s", absolutePath);
        log.info("编译指令：{}", compileCmd);
        try {
            //执行编译命令
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            log.info(executeMessage.toString());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return executeMessage;
    }

    /**
     * 3.执行代码，得到输出结果
     * @return
     */
    public List<ExecuteMessage> executeCode(List<String> inputList,String userCodeParentPath){
        //返回的判断用例执行信息集合
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        //增强for循环一一处理
        for (String inputArgs : inputList) {
            //String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            //String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath, SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASS_NAME, inputArgs);
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s %s", userCodeParentPath, MAIN_CLASS);
            log.info("运行指令：{}", runCmd);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                // 超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        log.info("time interrupted");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                //ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                //交互式进程，通过这里带入测试用例参数
                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess, inputArgs);
                log.info("执行代码后的运行结果：{}", executeMessage.toString());
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return executeMessageList;
    }

    /**
     * 4.封装响应结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse processResponse(List<ExecuteMessage> executeMessageList){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        long maxMemory = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            //如果存在错误信息,
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            Long memory = executeMessage.getMemory();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            if(memory != null){
                maxMemory = Math.max(maxMemory,memory);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5. 关闭资源
     *
     * @param userCodeFile
     * @param userCodeParentPath
     * @return
     */
    public boolean closeResource(File userCodeFile, String userCodeParentPath) {
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            log.info("删除{}", (del ? "成功" : "失败"));
            return del;
        }
        log.info("删除成功");
        return true;
    }

    /**
     * 6. 封装异常结果
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Exception e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(1);
        executeCodeResponse.setOutputList(new ArrayList<>());
        return executeCodeResponse;
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        log.info("请求数据模型：{}",executeCodeRequest);
        //获取数据模型的代码
        String code = executeCodeRequest.getCode();

        //1、将代码写入到文件
        File userCodeFile = saveCodeToFile(code);

        //2、编译代码,生成class文件
        ExecuteMessage executeMessage = compileCode(userCodeFile.getAbsolutePath());

        //3、执行代码，得到输出结果
        List<ExecuteMessage> executeMessages = executeCode(executeCodeRequest.getInputList(), userCodeFile.getParentFile().getAbsolutePath());

        //4、封装响应结果
        ExecuteCodeResponse executeCodeResponse = processResponse(executeMessages);

        //5、关闭资源
        boolean b = closeResource(userCodeFile, userCodeFile.getParentFile().getAbsolutePath());

        if (!b)
            throw new RuntimeException("关闭资源错误");
        return executeCodeResponse;
    }
}
